//
//  ChatViewController.m
//  MyWeChat
//
//  Created by 蔡欣东 on 15/10/5.
//  Copyright © 2015年 蔡欣东. All rights reserved.
//

#import "ChatViewController.h"
#import "MessageTableViewCell.h"
#import "FHInputToolbar.h"
#import "MessageDelegate.h"
#import "AppDelegate.h"
#import "Tools.h"
@interface ChatViewController ()<UITableViewDataSource,UITableViewDelegate,FHInputToolbarDelegate,MessageDelegate>{
    UserInfo* _friend;
    UserInfo* lordUser;
    FHInputToolbar* inputToolBar;
}
@end

@implementation ChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor grayColor];
    _tableView = [[UITableView alloc]init];
    _tableSource = [[NSMutableArray alloc]init];
    
    
    NSString* username = [[NSUserDefaults standardUserDefaults]valueForKey:USERNAME];
    lordUser = [[UserInfo alloc]initWithId:0 andName: username];

    [self getDataFromUserDefault];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:MessageTableViewCell.self forCellReuseIdentifier:[MessageTableViewCell reuseIdentifier]];
    _tableView.frame = CGRectMake(0,20, self.view.frame.size.width, self.view.frame.size.height-60-inputToolBar.frame.size.height);
    
    UIView* headerView = [[UIView alloc]init];
    headerView.frame = CGRectMake(0, 0, self.view.frame.size.width, 10);
    headerView.backgroundColor = [UIColor clearColor];
    _tableView.tableHeaderView = headerView;
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:_tableView];
    
    [self setupNavigationTitle: _friend.name];
    
    inputToolBar = [[FHInputToolbar alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height-44, [UIScreen mainScreen].bounds.size.width, 44)];
    inputToolBar.delegate = self;
    [self.view addSubview:inputToolBar];
    
    
  
    
    ((AppDelegate*)[UIApplication sharedApplication].delegate).messageDelegate = self;


    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardFrameWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [_tableView reloadData];
}

-(void)viewDidDisappear:(BOOL)animated{
    ((AppDelegate*)[UIApplication sharedApplication].delegate).messageDelegate = nil;
    
}

-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = NO;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - 通知后执行的方法
-(void)keyboardFrameWillChange:(NSNotification*) noti{
    NSDictionary* userInf = noti.userInfo;
    double duration = [[userInf objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect keyBoardFrame = [[userInf objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    [UIView animateWithDuration:duration animations:^{
        _tableView.frame = CGRectMake(0,20, self.view.frame.size.width, self.view.frame.size.height-0-inputToolBar.frame.size.height-keyBoardFrame.size.height);
        inputToolBar.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height-44-keyBoardFrame.size.height, [UIScreen mainScreen].bounds.size.width, 44);
    } completion:^(BOOL finished) {
        if (_tableSource.count>0) {
            NSIndexPath* path = [NSIndexPath indexPathForRow:_tableSource.count-1 inSection:0];
            [_tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:true];
        }
    
    }];
}
-(void)keyboardWillHide:(NSNotification*)noti{
    NSDictionary* userInfo = noti.userInfo;
    double duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
        _tableView.frame = CGRectMake(0,20, self.view.frame.size.width, self.view.frame.size.height-0-inputToolBar.frame.size.height);
        inputToolBar.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height-44, [UIScreen mainScreen].bounds.size.width, 44);
    }];
}

-(void)setupNavigationTitle:(NSString*) text{
    NSString* title = [text componentsSeparatedByString:@"@"][0];
    UILabel* titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 0, 220, 44)];
    titleLabel.text = title;
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont fontWithName:@"ChalkboardSE-Regular" size:18];
    self.navigationItem.titleView = titleLabel;
    
}
#pragma mark - tableview delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    [self getDataFromUserDefault];

    return _tableSource.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [MessageTableViewCell heightForCell:(MessageInfo*)_tableSource[indexPath.row]];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:[MessageTableViewCell reuseIdentifier]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_tableSource.count>0) {
        [cell setupMessageCell:(MessageInfo*)_tableSource[indexPath.row] andUser:lordUser];
    }

    
    return cell;
}

#pragma mark - scrollview delegate
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [inputToolBar.textField resignFirstResponder];
}

#pragma mark - 发送消息
-(void)onInputBtnTapped:(NSString *)text{
    if ([text isEqual:@""]) {
        return;
    }
    //xmpp
    
    if ([((AppDelegate*)[UIApplication sharedApplication].delegate).xmppStream1 isConnected]!= YES) {
        NSLog(@"连接失败");
        return;
    }
    
    MessageInfo* lastMessage = (MessageInfo*)_tableSource.lastObject;
    int lastid = lastMessage.messageId;
    MessageInfo* message = [[MessageInfo alloc]initWithId:lastid+1 andBody:text andTime:2.00 andUser:lordUser andImageUrl:@""];
    [_tableSource addObject:message];
    
    [self putInUserDefault:message];
    
    [_tableView reloadData];
    if (_tableSource.count>0) {
        NSIndexPath* path = [NSIndexPath indexPathForRow:_tableSource.count-1 inSection:0];
        [_tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
   
    //xmpp
    DDXMLElement* sendMessage = [DDXMLElement elementWithName:@"message"];
    [sendMessage addAttributeWithName:@"type" stringValue:@"chat"];
    [sendMessage addAttributeWithName:@"to" stringValue: _friend.name];
    [sendMessage addAttributeWithName:@"from" stringValue:lordUser.name];
    
    DDXMLElement* body = [DDXMLElement elementWithName:@"body"];
    [body setStringValue:text];
    [sendMessage addChild:body];
    NSLog(@"我发送的信息是%@",sendMessage);
    [((AppDelegate*)[UIApplication sharedApplication].delegate).xmppStream1 sendElement:sendMessage];
}
-(void)onLeftBtnTapped:(NSString *)text{

}

#pragma mark - 从外部传入friend
-(void)chatFriendDidChange:(UserInfo *)friend{
    _friend = friend;
    [self setupNavigationTitle:_friend.name];
    [_tableSource removeAllObjects];
    
    [_tableView reloadData];
}
#pragma mark - message delegate
-(void)didRecieveMessage:(MessageInfo *)messageInfo{
    if ([messageInfo.user.name isEqual:_friend.name]) {
        MessageInfo* message;
        if (_tableSource.count>0) {
            MessageInfo* lastMessage = (MessageInfo*)[_tableSource lastObject];
            int lastId = lastMessage.messageId;
            message = [[MessageInfo alloc]initWithId:lastId+1 andBody:messageInfo.messageBody andTime:2.00 andUser:messageInfo.user andImageUrl:@""];
        }else{
            message = [[MessageInfo alloc]initWithId:0 andBody:messageInfo.messageBody andTime:2.00 andUser:messageInfo.user andImageUrl:@""];
            NSLog(@"%@的第一条消息",_friend.name);
        }
            //[_tableSource addObject:message];
            [self putInUserDefault:message];
            [_tableView reloadData];
            //滚到最后一行
            NSIndexPath* path = [NSIndexPath indexPathForRow:_tableSource.count-1 inSection:0];
            [_tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];

        
    }else{
        NSString* otherUserName = [messageInfo.user.name componentsSeparatedByString:@"@"][0];
        NSString* newMessageInf = [NSString stringWithFormat:@"你有一条来自%@的信息",otherUserName];
        NSLog(@"%@",newMessageInf);
        [self otherFriendMsgPutInUserDefault:messageInfo];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"otherHaveNewMsg" object:nil userInfo:@{@"otherInfo":messageInfo}];
        [Tools showToast:newMessageInf];
        
        
    }
}



#pragma mark- 将消息存储在nsuserdefault和聊天记录的获取
-(void)putInUserDefault:(MessageInfo*)message{
    NSMutableArray* chatInfo = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:[NSString stringWithFormat:@"%@and%@msg",lordUser.name,_friend.name]]];
    NSMutableArray* chatUser = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:[NSString stringWithFormat:@"%@and%@",lordUser.name,_friend.name]]];
    [chatInfo addObject:message.messageBody];
    [chatUser addObject:message.user.name];
    NSLog(@"储存的消息是%@",message.messageBody);
    [[NSUserDefaults standardUserDefaults]setObject:chatInfo forKey:[NSString stringWithFormat:@"%@and%@msg",lordUser.name,_friend.name]];
    [[NSUserDefaults standardUserDefaults]setObject:chatUser forKey:[NSString stringWithFormat:@"%@and%@",lordUser.name,_friend.name]];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
-(void)otherFriendMsgPutInUserDefault:(MessageInfo*)message{
    NSMutableArray* chatInfo = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:[NSString stringWithFormat:@"%@and%@msg",lordUser.name,message.user.name]]];
    NSMutableArray* chatUser = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:[NSString stringWithFormat:@"%@and%@",lordUser.name,message.user.name]]];
    [chatInfo addObject:message.messageBody];
    [chatUser addObject:message.user.name];
    NSLog(@"储存的消息是%@",message.messageBody);
    [[NSUserDefaults standardUserDefaults]setObject:chatInfo forKey:[NSString stringWithFormat:@"%@and%@msg",lordUser.name,message.user.name]];
    [[NSUserDefaults standardUserDefaults]setObject:chatUser forKey:[NSString stringWithFormat:@"%@and%@",lordUser.name,message.user.name]];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
-(void)getDataFromUserDefault{
    [_tableSource removeAllObjects];
    NSLog(@"第一次");
    NSMutableArray* chatInfo = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:[NSString stringWithFormat:@"%@and%@msg",lordUser.name,_friend.name]]];
    NSMutableArray* chatUser = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:[NSString stringWithFormat:@"%@and%@",lordUser.name,_friend.name]]];
    for (int i =0; i<chatInfo.count; i++) {
        MessageInfo* newmsg = [[MessageInfo alloc]init];
        newmsg.messageBody = chatInfo[i];
        newmsg.user = [[UserInfo alloc]initWithId:0 andName:chatUser[i]];
        [_tableSource addObject:newmsg];
    }
    
}
@end
